import 'ol/ol.css'
import XYZ from 'ol/source/XYZ'
import { Map, View } from 'ol'
import { Tile } from 'ol/layer'
import { defaults as defaultControls } from 'ol/control'

import { Vector as VectorSource } from 'ol/source'
import { Vector as VectorLayer } from 'ol/layer'
import { createBox } from 'ol/interaction/Draw'
import { Draw } from 'ol/interaction'
import DoubleClickZoom from 'ol/interaction/DoubleClickZoom'
import { Circle as CircleStyle, Fill, Stroke, Style, Text, Icon } from 'ol/style'
import { unByKey } from 'ol/Observable.js'
import Overlay from 'ol/Overlay'
import { getArea, getLength } from 'ol/sphere.js'
import Feature from 'ol/Feature'
import Point from 'ol/geom/Point'
import { LineString, Polygon } from 'ol/geom.js'

import { Cluster } from 'ol/source'

import { Bus } from '@/utils/eventBus'
import army from '@/assets/mapView/army.png'
import { boundingExtent } from 'ol/extent'
import html2canvas from 'html2canvas'
import GeomCircle from 'ol/geom/Circle'
import arrow from '@/assets/mapView/arrow.png'
import WKT from 'ol/format/WKT'
// import { transform } from 'ol/proj'
// 平滑曲线
import smooth from 'chaikin-smooth'

let map = null
let draw = null
let vector
const cluster = {}
var leftTopX = 0
var leftTopY = 0
var RectWidth = 0
var RectHeight = 0
let timer
export function initMap(target, options = {}, config = { r: true }) {
  const KEY = 'd0c45508c851842ea4e34ec56780348c'
  const tianDiTu = {
    // 矢量
    vector: `https://t${Math.round(Math.random() * 7)}.tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=${KEY}`,
    vectorMark: 'http://t' + Math.round(Math.random() * 7) + '.tianditu.gov.cn/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=' + KEY,
    // 影像
    raster: 'http://t' + Math.round(Math.random() * 7) + '.tianditu.gov.cn/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=' + KEY,
    rasterMark: 'http://t' + Math.round(Math.random() * 7) + '.tianditu.gov.cn/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=' + KEY,
    // 地形
    topography: 'http://t' + Math.round(Math.random() * 7) + '.tianditu.gov.cn/DataServer?T=ter_w&x={x}&y={y}&l={z}&tk=' + KEY,
    topographyMark: 'http://t' + Math.round(Math.random() * 7) + '.tianditu.gov.cn/DataServer?T=cta_w&x={x}&y={y}&l={z}&tk=' + KEY
  }
  const tileUrlFunction = function(xyz) {
    const z = xyz[0]
    const x = xyz[1]
    const y = xyz[2]
    return `https://rt1.map.gtimg.com/realtimerender?z=${z}&x=${x}&y=${y}&type=vector&style=0&key=KSMBZ-3SMCV-LTYPU-UPYHY-GI2WF-UWBXB`
  }
  const crtlayerXYZ = function(id, url, visible, tileUrlFunction = function() { }) {
    return new Tile({
      source: new XYZ({
        url,
        crossOrigin: 'anonymous',
        tileUrlFunction
      }),
      properties: {
        layerId: 'TileLayers'
      },
      visible,
      id
    })
  }
  map = new Map({
    layers: [
      // 矢量
      crtlayerXYZ('VECTOR', tianDiTu.vector, !!config.v, tileUrlFunction),
      crtlayerXYZ('VECTORMARK', tianDiTu.vectorMark, !!config.v, tileUrlFunction),
      // 影像
      crtlayerXYZ('RASTER', tianDiTu.raster, !!config.r, tileUrlFunction),
      crtlayerXYZ('RASTERMARK', tianDiTu.rasterMark, !!config.r, tileUrlFunction),
      // 地形
      crtlayerXYZ('TOPOGRAPHY', tianDiTu.topography, !!config.t, tileUrlFunction),
      crtlayerXYZ('TOPOGRAPHYMARK', tianDiTu.topographyMark, !!config.t, tileUrlFunction)
    ],
    target: target,
    view: new View({
      projection: 'EPSG:4326',
      center: [100.871785, 36.959049],
      zoom: 6,
      maxZoom: 18,
      ...options
    }),
    controls: defaultControls({
      zoom: false,
      rotate: false,
      attribution: false
    })
  })
  _bindMapEvents()
}

export function getMap() {
  return map
}
// 绘制模式
export function addInteraction(type, name, isClickCloseMore) {
  let geometryFunction
  const source = new VectorSource()
  if (type) {
    disableMapDoubleClickZoom()
    // 点
    if (type === 'Point') {
      vector = new VectorLayer({
        style: new Style({
          fill: new Fill({
            color: 'rgba(255, 255, 255, 0.2)'
          }),
          stroke: new Stroke({
            color: '#DC143C',
            width: 2
          }),
          image: new CircleStyle({
            radius: 7,
            fill: new Fill({
              color: '#DC143C'
            })
          })
        }),
        source: source,
        id: 'Point' + name,
        properties: {
          layerId: 'drawId'
        },
        name: name
      })
      map.addLayer(vector)
    } else if (type === 'LineString') { // 直线
      vector = new VectorLayer({
        source: source,
        id: 'LineString' + name,
        properties: {
          layerId: 'drawId'
        },
        style: new Style({
          stroke: new Stroke({
            color: '#ffcc33',
            width: 2
          })
        }),
        name: name
      })
      map.addLayer(vector)
    } else if (type === 'Box') { // 矩形
      type = 'Circle'
      vector = new VectorLayer({
        source: source,
        id: 'Box' + name,
        properties: {
          layerId: 'drawId',
          type: 'rect'
        },
        style: new Style({
          fill: new Fill({
            color: 'rgba(255, 255, 255, 0.5)' // 0.1
          }),
          stroke: new Stroke({
            color: '#ffcc33',
            width: 2
          })
        }),
        name: name
      })
      map.addLayer(vector)
      geometryFunction = createBox()
    } else if (type === 'Polygon') { // 多变形
      vector = new VectorLayer({
        source: source,
        id: 'Polygon' + name,
        properties: {
          layerId: 'drawId'
        },
        style: new Style({
          fill: new Fill({
            color: 'rgba(255, 255, 255, 0.5)' // 0.1
          }),
          stroke: new Stroke({
            color: '#ffcc33',
            width: 2
          })
        }),
        name: name
      })
      map.addLayer(vector)
    } else if (type === 'Circle') { // 圆
      vector = new VectorLayer({
        source: source,
        id: 'Circle' + name,
        properties: {
          layerId: 'drawId'
        },
        style: new Style({
          fill: new Fill({
            color: 'rgba(255, 255, 255, 0.5)' // 0.1
          }),
          stroke: new Stroke({
            color: '#ffcc33',
            width: 2
          })
        }),
        name: name
      })
      map.addLayer(vector)
    } else if (type === 'Point1') { // 带文字的点
      type = 'Point'
      vector = new VectorLayer({
        style: new Style({
          text: new Text({
            font: '14px 微软雅黑,sans-serif',
            fill: new Fill({
              color: '#ff1824'
            }),
            stroke: new Stroke({
              color: '#ff1824',
              width: 1
            }),
            placement: 'point',
            // 标签的边框
            backgroundStroke: new Stroke({
              color: '#feff2a',
              width: 1
            }),
            // 标签的背景填充
            backgroundFill: new Fill({
              color: '#feff2a'
            }),
            text: name
          })
        }),
        source: source,
        id: 'Point1' + name,
        properties: {
          layerId: 'drawId'
        },
        name: name
      })
      map.addLayer(vector)
    } else if (type === 'lineArrow') { // 带箭头的直线
      type = 'LineString'
      const styleFunction = function(feature) {
        const geometry = feature.getGeometry()
        const styles = [
          // linestring
          new Style({
            stroke: new Stroke({
              color: '#ffcc33',
              width: 2
            })
          })
        ]
        geometry.forEachSegment(function(start, end) {
          const dx = end[0] - start[0]
          const dy = end[1] - start[1]
          const rotation = Math.atan2(dy, dx)
          // arrows
          styles.push(
            new Style({
              geometry: new Point(end),
              image: new Icon({
                src: arrow,
                anchor: [0.65, 0.5],
                rotateWithView: true,
                rotation: -rotation
              })
            })
          )
        })

        return styles
      }
      vector = new VectorLayer({
        source: source,
        properties: {
          layerId: 'drawId'
        },
        style: styleFunction
      })
      map.addLayer(vector)
    } else if (type === 'curve') { // 曲线
      type = 'LineString'
      const style = new Style({
        stroke: new Stroke({
          color: '#ffcc33',
          width: 2
        })
      })
      vector = new VectorLayer({
        source: source,
        properties: {
          layerId: 'drawId'
        },
        style: style
      })
      map.addLayer(vector)
    } else if (type === 'curveLineArrow') { // 带箭头的曲线
      type = 'LineString'
      const styleFunction = function(feature) {
        const geometry = feature.getGeometry()
        const styles = [
          new Style({
            stroke: new Stroke({
              color: '#ffcc33',
              width: 2
            })
          })
        ]
        let a
        geometry.forEachSegment(function(start, end) {
          const dx = end[0] - start[0]
          const dy = end[1] - start[1]
          const rotation = Math.atan2(dy, dx)
          a = rotation
        })
        styles.push(
          new Style({
            geometry: new Point(geometry.getLastCoordinate()),
            image: new Icon({
              src: arrow,
              anchor: [0.5, 0.5],
              rotateWithView: true,
              rotation: -a
            })
          })
        )
        return styles
      }
      vector = new VectorLayer({
        source: source,
        properties: {
          layerId: 'drawId'
        },
        style: styleFunction
      })
      map.addLayer(vector)
    }
    draw = new Draw({
      source: source,
      type: type,
      geometryFunction: geometryFunction
    })
  }
  draw.on('drawend', function(evt) {
    console.log('绘制结束啦！！', leftTopX, leftTopY, RectWidth, RectHeight)
    // 矩形截图
    if (geometryFunction) {
      var feature = evt.feature
      var extent = feature.getGeometry().getExtent()
      // 地理坐标转化为屏幕坐标
      var coord = [extent[0], extent[3]]
      var leftTopPosttion = map.getPixelFromCoordinate(coord)
      var coord1 = [extent[2], extent[1]]
      var bottomRightPosttion = map.getPixelFromCoordinate(coord1)
      // console.log('左上右下', leftTopPosttion, bottomRightPosttion)
      // 矩形宽高
      var width = Math.abs(bottomRightPosttion[0] - leftTopPosttion[0])
      var height = Math.abs(bottomRightPosttion[1] - leftTopPosttion[1])
      // console.log('宽高', width, height)
      // 矩形左上角坐标
      var minX = leftTopPosttion[0] <= bottomRightPosttion[0] ? leftTopPosttion[0] : bottomRightPosttion[0]
      var minY = leftTopPosttion[1] <= bottomRightPosttion[1] ? leftTopPosttion[1] : bottomRightPosttion[1]
      // console.log('左上角坐标', minX, minY)
      leftTopX = minX
      leftTopY = minY
      RectWidth = width
      RectHeight = height
    }
    // 曲线 曲箭头
    if (name === 'biaohuicurve' || name === 'biaohuicurveLineArrow') {
      const feat = evt.feature
      const geometry = feat.getGeometry()
      const coords = geometry.getCoordinates()
      const smoothened = makeSmooth(coords, parseInt(5, 10) || 5)
      geometry.setCoordinates(smoothened)
    }
    if (!isClickCloseMore) {
      Bus.$emit('closeMore', evt)
    }
    // 退出绘制模式
    map.removeInteraction(draw)
    map.once('dblclick', addLastPoint)
  })
  map.addInteraction(draw)
}
// 曲线
function makeSmooth(path, numIterations) {
  numIterations = Math.min(Math.max(numIterations, 1), 10)
  while (numIterations > 0) {
    path = smooth(path)
    numIterations--
  }
  return path
}

// 清除底图外的图层
export function clearAllLayers() {
  const layers = map.getLayers().getArray()
  const layer = layers.filter((item, index) => item.values_.layerId !== 'TileLayers')
  layer.forEach(item => {
    item.getSource().clear()
    map.getOverlays().clear()
  })
  leftTopX = 0
  leftTopY = 0
  RectWidth = 0
  RectHeight = 0
}

// 退出绘制模式
export function removeDraw() {
  if (draw) {
    map.removeInteraction(draw)
  }
}

// 禁用双击放大功能
function disableMapDoubleClickZoom() {
  const dblClickInteraction = map
    .getInteractions()
    .getArray()
    .find((interaction) => {
      return interaction instanceof DoubleClickZoom
    })
  if (dblClickInteraction) {
    map.removeInteraction(dblClickInteraction)
  }
}
// 开启双击放大功能
function enableMapDoubleClickZoom() {
  const dblClickInteraction = new DoubleClickZoom()
  map.addInteraction(dblClickInteraction)
}
function addLastPoint(event) {
  event.stopPropagation()
  enableMapDoubleClickZoom()
}

// 测量
export function measureAddInteraction(drawType) {
  const source = new VectorSource()
  var measureVector
  measureVector = new VectorLayer({
    source: source,
    style: new Style({
      fill: new Fill({
        color: 'rgba(255, 255, 255, 0.2)'
      }),
      stroke: new Stroke({
        color: 'rgba(255, 0, 0, 0.5)',
        lineDash: [10, 10],
        width: 2
      }),
      image: new CircleStyle({
        radius: 7,
        fill: new Fill({
          color: '#ffcc33'
        })
      })
    }),
    properties: {
      layerId: 'measureLayers'
    },
    zIndex: 16
  })
  measureVector.set('id', 'lineAndArea')
  map.addLayer(measureVector)
  // }
  /**
       * Currently drawn feature.
       * @type {module:ol/Feature~Feature}
       */
  let sketch
  /**
       * The help tooltip element.
       * @type {Element}
       */
  let helpTooltipElement
  /**
       * Overlay to show the help messages.
       * @type {module:ol/Overlay}
       */
  let helpTooltip
  /**
       * The measure tooltip element.
       * @type {Element}
       */
  let measureTooltipElement
  /**
       * Overlay to show the measurement.
       * @type {module:ol/Overlay}
       */
  let measureTooltip
  /**
       * Message to show when the user-manger is drawing a polygon.
       * @type {string}
       */
  const continuePolygonMsg = ''
  /**
       * Message to show when the user-manger is drawing a line.
       * @type {string}
       */
  const continueLineMsg = ''
  createMeasureTooltip()
  createHelpTooltip()
  /**
       * Handle pointer move.
       * @param {module:ol/MapBrowserEvent~MapBrowserEvent} evt The event.
       */
  const pointerMoveHandler = function(evt) {
    if (evt.dragging) {
      return
    }
    /** @type {string} */
    let helpMsg = '请点击开始绘制'

    if (sketch) {
      const geom = sketch.getGeometry()
      if (geom instanceof Polygon) {
        helpMsg = continuePolygonMsg
      } else if (geom instanceof LineString) {
        helpMsg = continueLineMsg
      }
    }

    helpTooltipElement.innerHTML = helpMsg
    helpTooltip.setPosition(evt.coordinate)
    helpTooltipElement.classList.remove('hidden')
  }

  map.on('pointermove', pointerMoveHandler)
  map.getViewport().addEventListener('mouseout', function() {
    if (helpTooltipElement) {
      helpTooltipElement.classList.add('hidden')
    }
  })

  const formatLength = function(line) {
    // 获取投影坐标系
    const sourceProj = map.getView().getProjection()
    // ol/sphere里有getLength()和getArea()用来测量距离和区域面积，默认的投影坐标系是EPSG:3857, 其中有个options的参数，可以设置投影坐标系
    const length = getLength(line, { projection: sourceProj })
    // let length = getLength(line);
    let output
    if (length > 100) {
      output = Math.round((length / 1000) * 100) / 100 + ' ' + 'km'
    } else {
      output = Math.round(length * 100) / 100 + ' ' + 'm'
    }
    return output
  }

  const formatArea = function(polygon) {
    // 获取投影坐标系
    const sourceProj = map.getView().getProjection()
    const area = getArea(polygon, { projection: sourceProj })
    // let area = getArea(polygon);
    // console.info(area)
    let output
    if (area > 10000) {
      output =
            Math.round((area / 1000000) * 100) / 100 + ' ' + 'km<sup>2</sup>'
    } else {
      output = Math.round(area * 100) / 100 + ' ' + 'm<sup>2</sup>'
    }
    return output
  }
  let measureDraw
  function addInteraction() {
    measureDraw = new Draw({
      source: source,
      type: drawType,
      style: new Style({
        fill: new Fill({
          color: 'rgba(255, 255, 255, 0.2)'
        }),
        stroke: new Stroke({
          color: 'rgba(0, 0, 0, 0.5)',
          lineDash: [10, 10],
          width: 2
        }),
        image: new CircleStyle({
          radius: 5,
          stroke: new Stroke({
            color: 'rgba(0, 0, 0, 0.7)'
          }),
          fill: new Fill({
            color: 'rgba(255, 255, 255, 0.2)'
          })
        })
      })
    })
    map.addInteraction(measureDraw)

    let listener
    measureDraw.on(
      'drawstart',
      function(evt) {
        // set sketch
        sketch = evt.feature
        // 禁用双击放大功能
        disableMapDoubleClickZoom()
        /** @type {module:ol/coordinate~Coordinate|undefined} */
        var tooltipCoord = evt.coordinate

        listener = sketch.getGeometry().on('change', function(evt) {
          var geom = evt.target
          var output
          if (geom instanceof Polygon) {
            output = formatArea(geom)
            tooltipCoord = geom.getInteriorPoint().getCoordinates()
          } else if (geom instanceof LineString) {
            output = formatLength(geom)
            tooltipCoord = geom.getLastCoordinate()
          }
          measureTooltipElement.innerHTML = output
          measureTooltipElement.style.color = 'yellow'
          measureTooltipElement.style.border = '2px solid lightblue'
          measureTooltipElement.style.borderRadius = '10px'
          measureTooltipElement.style.padding = '3px'
          measureTooltipElement.style.backgroundColor = 'gray'
          measureTooltip.setPosition(tooltipCoord)
        })
      },
      this
    )

    measureDraw.on(
      'drawend',
      function(event) {
        // 打开双击放大功能
        measureTooltipElement.className = 'tooltip tooltip-static'
        measureTooltip.setOffset([0, -7])
        // unset sketch
        sketch = null
        // unset tooltip so that a new one can be created
        measureTooltipElement = null
        createMeasureTooltip()
        unByKey(listener)
        map.un('pointermove', pointerMoveHandler)
        map.removeInteraction(measureDraw)
        helpTooltipElement.classList.add('hidden')
        // 地图双击事件
        map.once('dblclick', addLastPoint)
        if (measureTooltipElement) {
          helpTooltipElement.parentNode.removeChild(helpTooltipElement)
          helpTooltipElement = null
        }
      },
      this
    )
  }

  function createHelpTooltip() {
    if (helpTooltipElement) {
      helpTooltipElement.parentNode.removeChild(helpTooltipElement)
    }
    helpTooltipElement = document.createElement('div')
    helpTooltipElement.className = 'tooltip hidden'
    helpTooltip = new Overlay({
      element: helpTooltipElement,
      offset: [15, 0],
      id: 'helpTooltipElement',
      positioning: 'center-left'
    })
    map.addOverlay(helpTooltip)
  }

  function createMeasureTooltip() {
    if (measureTooltipElement) {
      measureTooltipElement.parentNode.removeChild(measureTooltipElement)
    }
    measureTooltipElement = document.createElement('div')
    measureTooltipElement.className = 'tooltip tooltip-measure'
    measureTooltip = new Overlay({
      element: measureTooltipElement,
      offset: [0, -15],
      id: 'measureTooltipElement',
      positioning: 'bottom-center'
    })
    map.addOverlay(measureTooltip)
  }

  // 量测调用
  addInteraction()
  // 绘制结束
}

// 聚合点添加
export function addCluster(layerId, data, imgs, colors) {
  const features = []
  for (let i = 0; i < data.length; i++) {
    features.push(
      new Feature({
        geometry: new Point(data[i].geometry.coordinates),
        properties: data[i].properties
      })
    )
  }
  const source = new VectorSource({
    features: features
  })
  var clusterSource = new Cluster({
    distance: parseInt(20, 10),
    minDistance: parseInt(10, 10),
    source: source
  })
  const styleCache = {}
  if (cluster[layerId]) {
    cluster[layerId].setSource(clusterSource)
  } else {
  // 创建图层
    cluster[layerId] = new VectorLayer({
      source: clusterSource,
      properties: {
        layerId: layerId
      },
      style: function(feature) {
        const size = feature.get('features').length
        const featureData = feature.get('features')
        let style = styleCache[size]
        let imgIcon = null
        if (featureData[0].values_.properties.extend && featureData[0].values_.properties.extend.icon) {
          imgIcon = featureData[0].values_.properties.extend.icon
        }
        let img
        if (imgIcon) {
          img = require(`@/assets/biaohui/${imgIcon}`)
        } else {
          img = imgs || army
        }
        if (!style) {
          if (size > 1) {
            let color
            let image
            featureData.forEach(item => {
              if (item.values_.properties.extend) {
                color = item.values_.properties.extend.color
                image = new CircleStyle({
                  radius: 12,
                  stroke: new Stroke({
                    color: color
                  }),
                  fill: new Fill({
                    color: color
                  })
                })
              } else {
                if (colors) {
                  color = colors
                } else {
                  color = 'red'
                }
                image = new CircleStyle({
                  radius: 12,
                  stroke: new Stroke({
                    color: color
                  }),
                  fill: new Fill({
                    color: color
                  })
                })
              }
            })
            style = new Style({
              image: image,
              text: new Text({
                text: size.toString(),
                fill: new Fill({
                  color: '#fff'
                })
              })
            })
          } else {
            style = new Style({
              image: new Icon({
                anchor: [16, 32],
                anchorXUnits: 'pixels',
                anchorYUnits: 'pixels',
                src: img
              })
            })
          }
          styleCache[size] = style
        }
        return style
      }
    })
    map.addLayer(cluster[layerId])
  }
}

// 清除聚合图层
export function removeClusterLayer(layerId) {
  const layers = map.getLayers().getArray()
  const layer = layers.find((item) => item.values_.layerId === layerId)
  if (layer) {
    map.removeLayer(layer)
    cluster[layerId] = null
  }
}

// 根据图层ID隐藏聚合图层
export function hideClusterLayerById(id) {
  const layers = map.getLayers().getArray()
  // console.log(layers)
  const layer = layers.find((item) => item.values_.layerId === id)
  if (layer) {
    layer.setVisible(false)
  }
}
// 根据图层ID显示聚合图层
export function showClusterLayerById(id) {
  const layers = map.getLayers().getArray()
  // console.log(layers)
  const layer = layers.find((item) => item.values_.layerId === id)
  if (layer) {
    layer.setVisible(true)
  }
}

// 地图事件
function _bindMapEvents() {
  map.on('click', (evt) => {
    // 根据中心点画圆的图层
    const layers = map.getLayers().getArray()
    const layer = layers.find((item) => item.values_.id === 'circleRadius')
    if (layer) {
      return false
    }
    const overLay = map.getOverlays().getArray()
    // console.log(overLay, 'overLay')
    if (overLay.length > 0) {
      overLay.forEach(item => {
        // 地图内容详情弹框
        if (item.getId() === 'toolTipBox') {
          item.setPosition(undefined)
        }
      })
    }
    for (var layerId in cluster) {
      if (cluster[layerId] !== null) {
        cluster[layerId].getFeatures(evt.pixel).then((clickedFeatures) => {
          if (clickedFeatures.length) {
            const features = clickedFeatures[0].get('features')
            if (features.length > 1) {
              const extent = boundingExtent(
                features.map((r) => r.getGeometry().getCoordinates())
              )
              map.getView().fit(extent, { duration: 1000, padding: [50, 50, 50, 50] })
            } else if (features.length === 1) {
              console.log(features, 'features')
              const obj = {
                evt: evt,
                feature: features[0]
              }
              Bus.$emit('getFeature', obj)
            }
          }
        })
      }
    }
    // 标记点击事件
    var feature = map.forEachFeatureAtPixel(
      evt.pixel,
      function(feature, layer) {
        return feature
      },
      {
        layerFilter: (layer) => {
          const ids = [
            'dizhi',
            'shanhong'
          ]
          if (layer.values_ && ids.indexOf(layer.values_.layerId || layer.values_.id) !== -1) {
            return true
          }
          return false
        },
        hitTolerance: 6
      }
    )
    if (feature) {
      if (feature.values_.properties && feature.values_.properties.id === 'circleRadius') {
        return false
      }
      const obj = {
        evt: evt,
        feature: feature
      }
      Bus.$emit('getMarkFeature', obj)
    }
  })
}

// 截图
export function onHandleScreenshot() {
  // 根据框选区域进行截图
  if (leftTopX !== 0 && leftTopY !== 0 && RectWidth !== 0 && RectHeight !== 0) {
    setTimeout(() => {
      const ref = document.getElementById('map')
      html2canvas(ref, {
        useCORS: true, // 是否尝试使用CORS从服务器加载图像
        backgroundColor: '#ececec', // 画布背景色（如果未在DOM中指定）。设置null为透明
        x: leftTopX,
        y: leftTopY,
        width: RectWidth,
        height: RectHeight
      }).then(canvas => {
        canvas.toBlob(function(blob) {
          const elelink = document.createElement('a')
          elelink.download = '框选截图'
          elelink.style.display = 'none'
          elelink.href = URL.createObjectURL(blob)
          document.body.appendChild(elelink)
          elelink.click()
          document.body.removeChild(elelink)
          leftTopX = 0
          leftTopY = 0
          RectWidth = 0
          RectHeight = 0
        }, 'image/png', 1)
      })
    }, 1000)
  } else {
    // 全屏截图
    setTimeout(() => {
      const ref = document.getElementById('map')
      html2canvas(ref, {
        useCORS: true, // 是否尝试使用CORS从服务器加载图像
        backgroundColor: '#ececec'
      }).then((canvas) => {
        canvas.toBlob(function(blob) {
          // saveAs(blob, '工作用图')
          const elelink = document.createElement('a')
          elelink.download = '全屏截图'
          elelink.style.display = 'none'
          elelink.href = URL.createObjectURL(blob)
          document.body.appendChild(elelink)
          elelink.click()
          document.body.removeChild(elelink)
        }, 'image/png', 1)
      })
    }, 1000)
  }
}

// 删除单个点 删除地图上图点覆盖物
export function clearMapPointLayers(id) {
  const lys = map.getLayers().getArray()
  const len = lys.length - 1
  for (let i = len; i > 0; i--) {
    if (lys[i].values_.id === id) {
      lys[i].getSource().clear()
      map.removeOverlay(lys[i])
    }
  }
}
// 根据图层ID隐藏图层
export function hideLayerById(id) {
  const layers = map.getLayers().getArray()
  // console.log(layers)
  const layer = layers.find((item) => item.values_.id === id)
  if (layer) {
    layer.setVisible(false)
  }
}

// 根据图层ID显示图层
export function showLayerById(id) {
  const layers = map.getLayers().getArray()
  const layer = layers.find((item) => item.values_.id === id)
  if (layer) {
    layer.setVisible(true)
  }
}
// 根据图层ID删除图层
export function removeLayers(id) {
  if (timer) {
    clearInterval(timer)
  }
  const layers = map.getLayers().getArray()
  const layer = layers.filter((item, index) => item.values_.id === id)
  layer.forEach(item => {
    map.removeLayer(item)
  })
}

// 地图上添加单个图点覆盖物
export function addPointInMap(coordinates, data, id) {
  const layers = map.getLayers().getArray()
  let layer = layers.find((item) => item.values_.id === id)
  if (layer) {
    layer.getSource().clear()
  } else {
    layer = new VectorLayer({
      source: new VectorSource(),
      properties: {
        id: id
      }
    })
    map.addLayer(layer)
  }
  const imgUrl = data['img'] ? data['img'] : require('../../assets/mapView/sign.png')
  // 创建矢量对象
  const feature = new Feature({
    geometry: new Point(coordinates),
    properties: data
  })
  feature.setStyle(
    new Style({
      image: new Icon({
        anchor: [16, 32],
        anchorXUnits: 'pixels',
        anchorYUnits: 'pixels',
        src: imgUrl
      })
    })
  )
  // 添加到之前的创建的layer中去
  layer.getSource().addFeature(feature)
}
// 地图上添加多个图点覆盖物
export function addMorePointInMap(coordinates, data, id) {
  const layers = map.getLayers().getArray()
  let layer = layers.find((item) => item.values_.id === id)

  if (layer) {
    layer.getSource().clear()
  } else {
    layer = new VectorLayer({
      source: new VectorSource(),
      properties: {
        id: id
      }
    })
    map.addLayer(layer)
  }
  const imgUrl = data['img'] ? data['img'] : require('../../assets/mapView/sign.png')
  for (let index = 0; index < coordinates.length; index++) {
    const element = coordinates[index]
    // 创建一个Feature，并设置好在地图上的位置
    const feature = new Feature({
      geometry: new Point(element),
      properties: element
    })
    // 设置样式，在样式中就可以设置图标
    feature.setStyle(
      new Style({
        image: new Icon({
          anchor: [16, 32],
          anchorXUnits: 'pixels',
          anchorYUnits: 'pixels',
          src: imgUrl
        })
      })
    )
    // 添加到之前的创建的layer中去
    layer.getSource().addFeature(feature)
  }
}

// 根据经纬度画圆
export function drawCircle(id, centerPoint, radius) {
  const layers = map.getLayers().getArray()
  let layer = layers.find((item) => item.values_.id === id)
  if (layer) {
    layer.getSource().clear()
  } else {
    layer = new VectorLayer({
      source: new VectorSource(),
      zIndex: 15,
      properties: {
        id: id
      }
    })
    map.addLayer(layer)
  }
  // 利用ol api 把半径米单位转换为EPSG:4326坐标系上的单位
  var metersPerUnit = map.getView().getProjection().getMetersPerUnit()
  var circleRadius = radius / metersPerUnit
  const feature = new Feature({
    // 圆的中心点
    geometry: new GeomCircle(centerPoint, Number(circleRadius)),
    properties: {
      id: id
    }
  })
  feature.setStyle(
    new Style({
      fill: new Fill({
        color: 'rgba(255, 255, 255, 0.5)' // 0.1
      }),
      stroke: new Stroke({
        color: '#ffcc33', // 0.8
        width: 2
      })
    })
  )
  // 添加到之前的创建的layer中去
  layer.getSource().addFeature(feature)
}

// 根据经纬度画线
export function addMoreLine(id, data) {
  const layers = map.getLayers().getArray()
  let layer = layers.find((item) => item.values_.id === id)
  if (layer) {
    layer.getSource().clear()
  } else {
    layer = new VectorLayer({
      source: new VectorSource({
        features: ''
      }),
      properties: {
        id: id
      },
      zIndex: 15,
      opacity: 1,
      typeName: 'wkttype'
    })
    map.addLayer(layer)
  }
  data.forEach(item => {
    const feature = new WKT().readFeature(item.geometry)
    feature.setProperties({
      element: item,
      id: id
    })
    const style = [
      new Style({
        fill: new Fill({
          color: 'black' // #0044CC
        }),
        stroke: new Stroke({
          width: 5,
          color: '#f00'
        })
      })
    ]
    const style2 = [
      new Style({
        fill: new Fill({
          color: 'black' // #0044CC
        }),
        stroke: new Stroke({
          width: 5,
          color: '#0f0'
        })
      })
    ]
    // 创建一个计数器来控制样式的交替
    var counter = 0
    // 设置一个定时器来定期更改样式
    timer = setInterval(function() {
      // 根据计数器的奇偶性来选择要应用的样式
      if (counter % 2 === 0) {
        feature.setStyle(style)
      } else {
        feature.setStyle(style2)
      }

      counter++
    }, 1000) // 每秒切换一次样式
    layer.getSource().addFeature(feature)
  })
}

// 点飞行
export function flyPoint(JDWD, zoom) {
  map.getView().animate({
    center: JDWD,
    zoom: zoom || 6,
    duration: 1800 // 飞行时间
  })
}
